package com.zpark.springboottest.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {
    // 捕获 MethodArgumentNotValidException 异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    //@ExceptionHandler注解中可以添加参数，参数是某个异常类的class，代表这个方法专门处理该类异常，也就是只有抛出Exception异常时候，才会调用该方法
    public Map<String, Object> handleMethodArgumentNotValidException(Throwable e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //Map<String,Objcet>哈希表  Key：value 形式
        String message = e.getMessage();
        map.put("msg", message);
        return map;
    }
}
